package com.baizhi.service.impl;

import com.baizhi.entity.*;
import com.baizhi.mapper.*;
import com.baizhi.service.IBzRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yu
 * @since 2020-10-14
 */
@Service
public class BzRoleServiceImpl extends ServiceImpl<BzRoleMapper, BzRole> implements IBzRoleService {
    @Autowired
    private BzAdminMapper bzAdminMapper;
    @Autowired
    private BzAdminRoleMapper bzAdminRoleMapper;
    @Autowired
    private BzRoleMapper bzRoleMapper;
    @Autowired
    private BzRolePermissionMapper bzRolePermissionMapper;
    @Autowired
    private BzMenuMapper bzMenuMapper;
    @Override
    public Set<String> getRolesByUsername(String username) {
        BzAdmin bzAdmin = bzAdminMapper.selectOne(new QueryWrapper<BzAdmin>().eq("username", username));
        if(bzAdmin==null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        List<BzAdminRole> roles = bzAdminRoleMapper.selectList(new QueryWrapper<BzAdminRole>().eq("admin_id", bzAdmin.getId()));
        HashSet<Integer> integers = new HashSet<>();
        for (BzAdminRole role : roles) {
            Integer roleId = role.getRoleId();
            integers.add(roleId);
        }
        List<BzRole> roleList = bzRoleMapper.selectList(new QueryWrapper<BzRole>().in("role_id", integers));
        HashSet<String> strings = new HashSet<>();
        for (BzRole bzRole : roleList) {
            String roleName = bzRole.getRoleName();
            strings.add(roleName);
        }
        return strings;
    }

    @Override
    public Set<String> getPermissionsByUsername(String username) {
        Set<String> rolesByUsername = getRolesByUsername(username);
        List<BzRolePermission> rolePermissionList = bzRolePermissionMapper.selectList(new QueryWrapper<BzRolePermission>().in("role_name", rolesByUsername));
        HashSet<Integer> integers = new HashSet<>();
        for (BzRolePermission bzRolePermission : rolePermissionList) {
            Integer perId = bzRolePermission.getPerId();
            integers.add(perId);
        }
        List<BzMenu> bzMenus = bzMenuMapper.selectList(new QueryWrapper<BzMenu>().in("menu_id", integers));
        HashSet<String> permissionStrings = new HashSet<>();
        for (BzMenu bzMenu : bzMenus) {
            permissionStrings.add(bzMenu.getPerms());
        }
        return permissionStrings;
    }
}
